
<template>
  <div>
    <el-tree
      ref="tree"
      :data="permission"
      :props="{label:'name'}"
      show-checkbox
      node-key="id"
      check-strictly
      default-expand-all
    />

    <div class="footer">
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRolesDetail, getRolesPermission } from '@/api/roles'
export default {
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permission: []
    }
  },
  created() {
    // 获取所有的权限列表
    this.loadPermission()
    // 获取当前的角色拥有的权限
    this.loadRolesDetail()
  },
  methods: {
    // 获取所有的权限列表
    async loadPermission() {
      try {
        // 1发请求
        const res = await getPermissionList()
        // console.log(res)
        // 把平铺数据转为树形结构
        this.permission = tranListToTreeData(res.data)
      } catch (e) {
        console.log(e)
      }
    },

    async hSubmit() {
      try {
        // 获取以勾选的权限
        const ids = this.$refs.tree.getCheckedKeys()
        // console.log(ids)
        // 发请求保存数据
        const res = await getRolesPermission({ id: this.id, permIds: ids })
        // console.log(res)
        // 提醒用户
        this.$message.success(res.message)
        // 关闭 dialog
        this.$emit('close')
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    async loadRolesDetail() {
      try {
        const res = await getRolesDetail(this.id)
        // console.log(res)
        // 设置当前已勾选的权限
        this.$refs.tree.setCheckedKeys(res.data.permIds)
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  display: flex;
  justify-content: end;
}
</style>
